from openai import OpenAI
import requests
import json

from _request.config import apiKey

def models_list(apiKey):
    client = OpenAI(api_key= apiKey, base_url="https://api.deepseek.com")
    print(client.models.list())
    return client.models.list()

def user_balance(token):
    url = "https://api.deepseek.com/user/balance"

    payload = {}
    headers = {
        'Accept': 'application/json',
        'Authorization': 'Bearer {}'.format(token)
    }

    response = requests.request("GET", url, headers=headers, data=payload)

    print(response.text)
    return response.text

def ask_question_by_request(apiKey, models = "deepseek-chat", question = "Hi"):
    url = "https://api.deepseek.com/chat/completions"

    payload = json.dumps({
        "messages": [
            {
                "content": "You are a helpful assistant",
                "role": "system"
            },
            {
                "content": "{}".format(question),
                "role": "user"
            }
        ],
        "model": "{}".format(models),
        "frequency_penalty": 0,
        "max_tokens": 2048,
        "presence_penalty": 0,
        "response_format": {
            "type": "text"
        },
        "stop": None,
        "stream": False,
        "stream_options": None,
        "temperature": 1,
        "top_p": 1,
        "tools": None,
        "tool_choice": "none",
        "logprobs": False,
        "top_logprobs": None
    })
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer {}'.format(apiKey)
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    print(response.text)

def ask_question_by_OpenAI_SDK(apiKey, models = "deepseek-chat", question = "Hello"):
    # for backward compatibility, you can still use `https://api.deepseek.com/v1` as `base_url`.
    client = OpenAI(api_key="{}".format(apiKey), base_url="https://api.deepseek.com")

    response = client.chat.completions.create(
        model="{}".format(models),
        messages=[
            {"role": "system", "content": "You are a helpful assistant"},
            {"role": "user", "content": "{}".format(question)},
        ],
        max_tokens=1024,
        temperature=0.7,
        stream=False
    )

    print(response.choices[0].message.content)


if __name__ == "__main__":
    models_list(apiKey)
    user_balance(apiKey)

    ask_question_by_request(apiKey, question="很高兴认识你，介绍一下你自己吧")